package com.rtx.wms.std.handler.cancle;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.common.HttpServletRequestUtil;
import com.rtx.edi.platform.field.service.PlFieldMappingService;
import com.rtx.model.dto.edi.EdiInnerRequestDTO;
import com.rtx.wms.std.asn.bean.ApiReceipt;
import com.rtx.wms.std.asn.bean.Receipt;
import com.rtx.wms.std.asn.service.ApiReceiptService;
import com.rtx.wms.std.asn.service.ReceiptService;
import com.rtx.wms.std.so.bean.ApiCancle;
import com.rtx.wms.std.so.bean.ApiOrders;
import com.rtx.wms.std.so.bean.Orderdetail;
import com.rtx.wms.std.so.bean.Orders;
import com.rtx.wms.std.so.service.ApiCancleService;
import com.rtx.wms.std.so.service.ApiOrdersService;
import com.rtx.wms.std.so.service.OrdersService;

/**
 * 订单取消
 */
@Component
public class WmsCancelHandler {

	Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    PlFieldMappingService plFieldMappingService;
    
    @Autowired
    ApiOrdersService apiOrdersService;
    
    @Autowired
    OrdersService ordersService;
    
    @Autowired
    ApiReceiptService apiReceiptService;
    
    @Autowired
    ReceiptService receiptService;
    
    @Autowired
    ApiCancleService apiCancleService;
    
    
    
    public String ordersCancel(HttpServletRequest request){

		Map<String,Object> response = new HashMap<>();
		response.put("whseid", "WMWHSE1");
		response.put("storerkey", "CATECH");
		
		String msg = "";
		try {
			String requestStr = HttpServletRequestUtil.getHttpBody(request);
			EdiInnerRequestDTO dto = JSON.parseObject(requestStr, EdiInnerRequestDTO.class);
			
			JSONObject requestData = JSON.parseObject(dto.getTagetjson(), JSONObject.class);
			String type = requestData.getString("type");
			String externkey = requestData.getString("externkey");
			String whseid = requestData.getString("whseid");
			response.put("externkey", externkey);
			
			
			String wemsDatatype = plFieldMappingService.queryWmsDataType("ris_edi", type);
			if("SO".equals(wemsDatatype)) {
				ordersCancel(whseid,externkey);
			}else if("ASN".equals(wemsDatatype)) {
				receiptCancel(whseid,externkey);
			}
		} catch (Exception e) {
			msg = e.getMessage();
			log.error("单据编辑前校对异常",e);
		}

		if(!"ok".equals(msg)) {
			response.put("code", "500");
			response.put("msg", msg);
		}else {
			response.put("code", "200");
			response.put("msg", msg);
		}
		
		return JSON.toJSONString(response);
	
    }
    
    
    public void ordersCancel(String whseid, String externorderkey) {
    	LambdaQueryWrapper<ApiOrders> apiordersQuery = Wrappers.lambdaQuery();
    	apiordersQuery.eq(ApiOrders::getExternorderkey, externorderkey);
    	List<ApiOrders> olist = apiOrdersService.selectApiOrdersByWrapperNoDetail("ris_edi", apiordersQuery);

    	String P_Status = "";
    	String PS_Status = "";
    	String PF_Status = "";
    	String PC_Status = ""; 
    	if(olist.size() > 0) {
    		for(ApiOrders mo:olist) {
    			if("PS".equals(mo.getEdiflag())) {
    				PS_Status ="true";
    			}
    			if("PF".equals(mo.getEdiflag())) {
    				PF_Status ="true";
    			}
    			if("P".equals(mo.getEdiflag())) {
    				P_Status ="true";
    			}
    			if("PC".equals(mo.getEdiflag())) {
    				PC_Status ="true";
    			} 
    		}
    	}
    	
    	if("true".equals(PC_Status)) {
    		return;
    	}else if("true".equals(P_Status) || "true".equals(PF_Status)) {
    		LambdaUpdateWrapper<ApiOrders> apiOrdersUpd = Wrappers.lambdaUpdate();
    		apiOrdersUpd.eq(ApiOrders::getExternorderkey,externorderkey);
    		apiOrdersUpd.set(ApiOrders::getEdiflag, "PC");
    		apiOrdersUpd.set(ApiOrders::getEditdate, LocalDateTime.now());
    		apiOrdersUpd.set(ApiOrders::getEditwho, "api");
    		apiOrdersService.updateByWrapper("ris_edi", apiOrdersUpd);
    		ApiCancle apicancle = new ApiCancle();
    		apicancle.setType("so");
    		apicancle.setExternkey(externorderkey);
    		apicancle.setEdiflag("P");
    		apiCancleService.addApiCancle("ris_edi", apicancle);
    	}else if("true".equals(PS_Status)) {
    		//【出库单取消逻辑】判断“ORDERCODE外部单号”查询ORDERS表中是否存在
    		//不存在，接口返回MESSAGE错误信息“XX单号不存在”，返回状态FLAG为failure。
    		//存在：判断ORDERS表单据状态值是否大于RTX_ORDERCANCEL值,小于“98外部取消，99内部取消”
    		//是，则接口返回MESSAGE错误信息“XX单号已发货”，返回状态FLAG为failure
    		//否，返回状态FLAG为success成功。当订单状态为“02外部创建、04内部创建、06未分配、08已转换、09未开始”时，更新订单STATUS、RTXCANCEL状态为“98外部取消”，否则更新订单RTXCANCEL状态为“98外部取消”。
    		LambdaQueryWrapper<Orders> ordersQuery = Wrappers.lambdaQuery();
    		ordersQuery.eq(Orders::getExternorderkey,externorderkey);
    		List<Orders> ordersList =ordersService.selectOrdersByWrapper(whseid, ordersQuery);
    		Assert.notEmpty(ordersList,"出库单：" + externorderkey + "处理中取消失败");
    		LambdaUpdateWrapper<Orders> update = Wrappers.lambdaUpdate();
    		update.eq(Orders::getExternorderkey,externorderkey)
    		.set(Orders::getRtxcancelmark,"98")
    		.set(Orders::getRtxcancel,"98")
    		.set(Orders::getRtxcanceldate,new Date());
    		Orders orders = ordersList.get(0);
    		int status = Integer.parseInt(orders.getStatus());
    		if(status >67 && status < 95) {
    			throw new RuntimeException("出库单：" + externorderkey + "已复合");
    		}
    		if(status == 95){
    			throw new RuntimeException("出库单：" + externorderkey + "已发货");
    		}
    		if(status < 10 || status==98){
    			update.set(Orders::getStatus,"98");
    			update.set(Orders::getOpenqty, "0");

    			//更新明细
    			LambdaUpdateWrapper<Orderdetail> odUpdate = Wrappers.lambdaUpdate();
    			odUpdate.eq(Orderdetail::getExternorderkey,externorderkey)
    			.set(Orderdetail::getOpenqty, "0")
    			.set(Orderdetail::getStatus,"98");
    			
    			ordersService.updatedetailByWrapper(null, odUpdate);
    		}
    		ordersService.updateByWrapper(null, update);
    	}else {
    		throw new RuntimeException("取消失败-单据在wms中不存在");
    	}
    }
    
    
  public void receiptCancel(String whseid, String externreceiptkey) {
		
        LambdaQueryWrapper<ApiReceipt> rquery = Wrappers.lambdaQuery();
        rquery.eq(ApiReceipt::getExternreceiptkey, externreceiptkey);
        List<ApiReceipt> rList = apiReceiptService.selectApiReceiptByWrapperNoDetail("ris_edi", rquery);
    	String P_Status = "";
		String PS_Status = "";
		String PF_Status = "";
		String PC_Status = "";
		
		for(ApiReceipt r:rList) {
			if("PS".equals(r.getEdiflag())) {
				PS_Status ="true";
			}
			if("PF".equals(r.getEdiflag())) {
				PF_Status ="true";
			}
			if("P".equals(r.getEdiflag())) {
				P_Status ="true";
			}
			if("PC".equals(r.getEdiflag())) {
				PC_Status ="true";
			}
		}
		
		if("true".equals(PC_Status)) {
    		return;
    	}else if("true".equals(P_Status) || "true".equals(PF_Status)) {
    		LambdaUpdateWrapper<ApiReceipt> apiOrdersUpd = Wrappers.lambdaUpdate();
    		apiOrdersUpd.eq(ApiReceipt::getExternreceiptkey,externreceiptkey);
    		apiOrdersUpd.set(ApiReceipt::getEdiflag, "PC");
    		apiOrdersUpd.set(ApiReceipt::getEditdate, LocalDateTime.now());
    		apiReceiptService.updateByWrapper(whseid, apiOrdersUpd);
    		ApiCancle apicancle = new ApiCancle();
    		apicancle.setType("asn");
    		apicancle.setExternkey(externreceiptkey);
    		apicancle.setEdiflag("P");
    		apiCancleService.addApiCancle("ris_edi", apicancle);
		}else if("true".equals(PS_Status)) {
	        //【收货单取消逻辑】根据“外部单号”查询RECEIPT表中是否存在
	        //不存在，接口返回MESSAGE错误信息“XX单号不存在”，返回状态FLAG为failure
	        //存在：
	        //当RECEIPT表单据状态>“4收货中”<“20已取消”，则接口返回MESSAGE错误信息“XX单号已收货”，返回状态FLAG为failure
	        //当RECEIPT表单据状态<“4收货中”，订单取消标记更新为“20已取消”，返回状态FLAG为success成功。
	        LambdaQueryWrapper<Receipt> query = Wrappers.lambdaQuery();
	        query.eq(Receipt::getExternreceiptkey,externreceiptkey);
	        List<Receipt> receiptList = receiptService.selectReceiptByWrapper(whseid, query);
	        Assert.notEmpty(receiptList,"入库单：" + externreceiptkey + "不存在");
	        Receipt receipt = receiptList.get(0);
	        int status = Integer.parseInt(receipt.getStatus());
	        if(status > 4 && status < 20){
	            throw new RuntimeException("入库单：" + externreceiptkey + "已收货");
	        }else{
	            if(status != 20){
	                LambdaUpdateWrapper<Receipt> update = Wrappers.lambdaUpdate();
	                update.eq(Receipt::getExternreceiptkey,externreceiptkey).set(Receipt::getStatus,"20");
	                receiptService.updateByWrapper(whseid, update);
	            }
	        }
		}else {
			throw new RuntimeException("取消失败-单据在wms中不存在");
		}

    }
}
